package com.res.service.impl;

import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.res.entity.Computer;
import com.res.entity.Readroom;
import com.res.repository.ComputerRepository;
import com.res.service.ComputerService;

@Service
public class ComputerServiceImpl implements ComputerService {
	@Autowired
	private ComputerRepository rep;

	@Override
	public Page<Computer> getComputerAll(Computer c, Pageable pageable, Integer cid) {
		return rep.findAll(get(c, cid), pageable);
	}

	public Specification<Computer> get(Computer c, Integer cid) {
		return new Specification<Computer>() {

			@Override
			public Predicate toPredicate(Root<Computer> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {

				Predicate predicate = criteriaBuilder.conjunction();
				List<Expression<Boolean>> expressions = predicate.getExpressions();
				if (cid != null && cid != 0) {
					expressions.add(criteriaBuilder.like(root.get("cid"), "%" + c.getCid() + "%"));
					expressions.add(criteriaBuilder.equal(root.get("readRoom").get("cid"), cid));
				}
				return predicate;
			}
		};
	}

	@Override
	public String addComputer(Computer c, Integer cid) {
		try {
			c.setReadRoom(new Readroom(cid, null));
			rep.save(c);
			return "添加成功";
		} catch (Exception e) {
			e.printStackTrace();
			return "添加失败";
		}
	}

	@Override
	public String updateComputer(Computer c, Integer cid) {
		try {
			c.setReadRoom(new Readroom(cid, null));
			rep.save(c);
			return "修改成功";
		} catch (Exception e) {
			e.printStackTrace();
			return "修改失败";
		}
	}

	@Override
	public String deleteComputer(Integer cid) {
		try {
			rep.deleteById(cid);
			return "删除成功";
		} catch (Exception e) {
			e.printStackTrace();
			return "删除失败";
		}
	}

}
